package com.itheima.service;

import com.itheima.client.userpojo.User;
import com.itheima.client.userpojo.dto.UserDto;
import com.itheima.client.userpojo.vo.UserVo;
import com.itheima.common.SnowFlake;
import com.itheima.mapper.client.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wuzhiyong
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SnowFlake snowFlake;

    /**
     * 登陆
     *
     * @param userDto userDto
     * @return userVo
     */
    public UserVo login(UserDto userDto) {
        //获取手机号，验证码
        String phone = userDto.getPhone();
        String code = userDto.getCode();

        //从redis中获取存入的验证码
        String codeRedis = redisTemplate.opsForValue().get(phone);
        //当登陆用验证码与redis相同则登陆成功
        if (code.equals(codeRedis)) {
            //查询该手机号是否存在
            UserVo userVo = userMapper.selectPhone(phone);
            if (userVo != null) {
                //生产token
                String s = System.currentTimeMillis() + userVo.getId();
                String token = DigestUtils.md5DigestAsHex(s.getBytes());

                //存入token并以userid为value
                redisTemplate.opsForValue().set(token, userVo.getId(), 7, TimeUnit.DAYS);
                userVo.setToken(token);
                return userVo;
            //手机号不存在为初次登陆则进行注册后登陆
            } else {
                //通过雪花算法获取id
                long id = snowFlake.nextId();

                //组装实体进行注册
                User user = new User();
                user.setId(String.valueOf(id));
                user.setPhone(phone);
                user.setStatus(1);
                userMapper.insertUser(user);

                //登陆
                String s = System.currentTimeMillis() + user.getId();
                String token = DigestUtils.md5DigestAsHex(s.getBytes());
                redisTemplate.opsForValue().set(token, user.getId(), 7, TimeUnit.DAYS);

                //组装响应体
                UserVo userVologon = new UserVo();
                userVologon.setToken(token);
                userVologon.setId(user.getId());
                userVologon.setPhone(user.getPhone());
                userVologon.setStatus(user.getStatus());
                return userVologon;
            }
        }
        return null;
    }

    /**
     * 登出
     * @param request request
     */
    public void logout(HttpServletRequest request) {

        String token = request.getHeader("AuthorizationUser");
        if (token != null) {
            String userId = redisTemplate.opsForValue().get(token);
            if (userId != null) {
                //获取手机号
                UserVo userVo = userMapper.selectById(userId);
                String phone = userVo.getPhone();
                //删除key phone
                if (phone != null && !"".equals(phone)) {
                    redisTemplate.delete(phone);
                }
            }
        }
        //删除key token
        if (token != null && !"".equals(token)) {
            redisTemplate.delete(token);
        }
    }
}
